<?php
include('admin.php');
set_page_info('id', 'posts');

if (ACTION == 'edit') {
	$id = (int)get_global($_GET, 'id');
	$post = get_single_item(array(
		'table' => POSTS,
		'class' => 'post',
		'where' => '`post_id` = "'.$id.'"'
	));
	if (empty($post)) error('That is not a valid post.');
	$categories = new items(array(
		'table' => CATEGORIES,
		'class' => 'category'
	));
	$category_ids = get_ids($categories);
	$this_category_ids = explode(',', $post->category);
	$users = new items(array(
		'table' => USERS,
		'class' => 'user'
	));
	
	if (isset($_POST['submit'])) {
		$c = get_post_data();
		$c['date'] = mktime($c['hour'], $c['minute'], date('s'), $c['month'], $c['day'], $c['year']);
		$c['date'] -= (60 * 60 * (int)get_option('timeoffset'));
		$c['date'] = get_date($dateFormats['mysql'], $c['date']);
		
		/***TITLE AND CONTENT***/
		if (empty($c['title'])) $c['title'] = $post->title;
		if (empty($c['content'])) $c['content'] = $post->content;
		else $c['content'] = clean($_POST['content'], true);
		
		/***SLUG***/
		if (empty($c['slug'])) $c['slug'] = get_slug($c['title']);
		$amount = (int)mysql_result($mysql->query('SELECT COUNT(*) FROM `'.POSTS.'` WHERE `post_title_slug` = "'.escape($c['slug']).'" AND `post_id` != "'.$post->get_id().'"'), 0);
		if ($amount > 0) $c['slug'] = $c['slug'].'-'.$amount;
		unset($amount);
		
		/***CATEGORIES***/
		$c['categories'] = (!empty($c['categories']) && is_array($c['categories']) && count($c['categories']) > 0) ? array_intersect($c['categories'], $category_ids) : (array)1;
		$c['categories'] = implode(',', (count($c['categories']) > 0) ? $c['categories'] : (array)1);
		
		/***USERS***/
		if (empty($c['user']) || !in_array($c['user'], get_ids($users))) $c['user'] = currentuser()->get_id();
		
		/***CUSTOM FIELDS***/
		$c['custom_fields'] = array();
		if (!empty($c['custom_key']) && !empty($c['custom_value']) && count($c['custom_key']) > 0 && count($c['custom_value']) > 0 && count($c['custom_key']) === count($c['custom_value'])) {
			foreach($c['custom_key'] as $key => $value) {
				$c['custom_fields'][$value] = $c['custom_value'][$key];
			}
		}
		
		/***COMMENTS AND STATUS***/
		$c['comments'] = (int)$c['comments'];
		if (empty($c['comments'])) $c['comments'] = 0;
		else $c['comments'] = 1;
		
		$c['status'] = (int)$c['status'];
		if (empty($c['status'])) $c['status'] = 0;
		else $c['status'] = 1;
		
		$result = $mysql->update(POSTS, array(
			'post_title' => $c['title'],
			'post_title_slug' => $c['slug'],
			'post_date' => $c['date'],
			'post_category' => $c['categories'],
			'post_content' => $c['content'],
			'post_excerpt' => $c['excerpt'],
			'post_status' => $c['status'],
			'post_comments' => $c['comments'],
			'post_titletag' => $c['titletag'],
			'post_metatag' => $c['metatag'],
			'post_author' => $c['user'],
			'post_custom_fields' => (count($c['custom_fields']) > 0) ? serialize($c['custom_fields']) : ''
		), '`post_id` = "'.$post->get_id().'"');
		if ($result === true) header('Location: posts.php#post-'.$id);
		else error('There was an error saving the post.');
	} else {
		set_page_info('title', 'Editing Post: '.$post->get_title());
		get_header();
?>
		<h2>Editing Post: <?php $post->the_title(); ?></h2>
		<form action="posts.php?action=edit&amp;id=<?php $post->the_id(); ?>" method="post">
			<p><label for="title">Title</label>
			<input type="text" name="title" id="title" class="slug" value="<?php $post->the_title(); ?>" /></p>
			
			<p><label for="slug">Slug</label>
			<input type="text" name="slug" id="slug" class="slughere" value="<?php $post->the_slug(); ?>" /></p>
			  <p>
            <label for "titletag">Title Tag</label>
            <input type="text" name="titletag" id="titletag" value="<?php print $post->get_titletag(); ?>" />
            </p>
            
             <p>
            <label for "metatag">Meta Tag</label>
            <input type="text" name="metatag" id="metatag" value="<?php print $post->get_metatag(); ?>" />
            </p>
			<p><label for="content">Content</label>
			<textarea name="content" id="content" class="large" rows="6" cols="60"><?php $post->the_content(false); ?></textarea>
            <script type="text/javascript">
				var oEdit1 = new InnovaEditor("oEdit1");
				oEdit1.cmdAssetManager="modalDialogShow('/admin/editor/assetmanager/assetmanager.php',640,445);";
				oEdit1.REPLACE("content");
			</script>
            
            </p>
			
			<p><label for="excerpt">Excerpt</label>
			<textarea name="excerpt" id="excerpt" class="small" rows="6" cols="60"><?php $post->the_excerpt(false, false); ?></textarea></p>
			
			<p>
				<label for="slug">Categories</label>
<?php foreach($allCategories->items as $category) { ?>
				<input type="checkbox" name="categories[]" id="categories[<?php $category->the_id(); ?>]" class="checkbox" value="<?php $category->the_id(); ?>"<?php if (in_array($category->get_id(), $this_category_ids)) echo ' checked="checked"'; ?> /> <label for="categories[<?php $category->the_id(); ?>]" class="checkboxlabel"><?php $category->the_name(); ?></label>
<?php } ?>
			</p>
			
			<p>
				<label>Date</label>
				<select name="month" id="month">
<?php $current = (int)$post->get_date('n'); for($i=1;$i<=12;$i++) { ?>
					<option value="<?php echo $i; ?>"<?php if ($i === $current) echo ' selected="selected"'; ?>><?php echo get_date('M', mktime(0, 0, 0, $i)); ?></option>
<?php } ?>
				</select>
				
				<input type="text" name="day" id="day" value="<?php echo $post->get_date('j'); ?>" /> , <input type="text" name="year" id="year" value="<?php echo $post->get_date('Y'); ?>" /> @ <input type="text" name="hour" id="hour" value="<?php echo $post->get_date('H'); ?>" /> : <input type="text" name="minute" id="minute" value="<?php echo $post->get_date('i'); ?>" />
			</p>
			
           
            
			<div class="paragraph">
				<label>Custom Fields</label>
				<div id="custom_fields">
					<div id="fields">
<?php
if (!empty($post->custom_fields)) {
	$custom_fields = unserialize($post->custom_fields);
	foreach($custom_fields as $key => $value) {
?>
						<div class="field">
							<div class="left">
								<input type="text" name="custom_key[]" class="custom_key" value="<?php echo $key; ?>" />
								<input type="submit" class="button custom_delete" value="Delete" />
							</div>
							<textarea name="custom_value[]" class="custom_value" rows="3" cols="30"><?php echo $value; ?></textarea>
						</div>
<?php
	}
}
?>
					</div>
					<div class="field">
						<div class="left">
							<input type="text" id="js_custom_key" />
							<input type="submit" id="js_save_custom_field" class="button" value="Save" />
						</div>
						
						<textarea id="js_custom_value" rows="3" cols="30"></textarea>
					</div>
				</div>
			</div>
			
			<p>
				<label for="comments">Allow Comments</label>
				<input type="radio" name="comments" id="comments[0]" class="radio" value="1"<?php if ($post->get_comment_status()) echo ' checked="checked"'; ?> /> <label for="comments[0]" class="radiolabel">Yes</label>
				<input type="radio" name="comments" id="comments[1]" class="radio" value="0"<?php if (!$post->get_comment_status()) echo ' checked="checked"'; ?> /> <label for="comments[1]" class="radiolabel">No</label>
			</p>
			
			<p>
				<label for="comments">Status</label>
				<input type="radio" name="status" id="status[0]" class="radio" value="1"<?php if ($post->get_status()) echo ' checked="checked"'; ?> /> <label for="status[0]" class="radiolabel">Published</label>
				<input type="radio" name="status" id="status[1]" class="radio" value="0"<?php if (!$post->get_status()) echo ' checked="checked"'; ?> /> <label for="status[1]" class="radiolabel">Draft</label>
			</p>
			
			<p>
				<label for="user">Author</label>
				<select name="user" id="user">
<?php foreach($users->items as $user) { ?>
					<option value="<?php $user->the_id(); ?>"<?php if ($post->get_author_object()->get_id() == $user->get_id()) echo ' selected="selected"'; ?>><?php $user->display_name(); ?></option>
<?php } ?>
				</select>
			</p>
			
			<p><input type="submit" name="submit" class="button" value="Save" accesskey="s" /></p>
		</form>
<?php
		get_footer();
	}
} elseif (ACTION == 'delete') {
	$id = (int)get_global($_GET, 'id');
	$result = delete_post($id);
	
	if ($result === true) header('Location: posts.php');
	else error('There was an error deleting the post.');
} else {
	$approved = get_posts(array(
		'paginationVar' => 'approved'
	), true);
	$unapproved = get_posts(array(
		'where' => '`post_status` = "0" OR `post_date` > NOW()',
		'paginationVar' => 'unapproved'
	));
	set_page_info('title', 'Manage Posts');
	get_header();
	
	if ($approved->total > 0) {
?>
		<h2>Approved Posts <small>(<?php echo $approved->total; ?>)</small> <span>(<a href="write.php">add one?</a>)</span></h2>
		<form action="mass-delete.php?type=posts" method="post">
			<table width="100%">
				<thead>
					<tr>
						<th><input type="checkbox" /></th>
						<th>Title</th>
						<th>Date</th>
						<th>Categories</th>
						<th>Comments</th>
						<th>&nbsp;</th>
					</tr>
				</thead>
				<tfoot>
					<tr>
						<td colspan="6">
							<input type="submit" name="submit" class="button" value="Delete" />
							Page: <?php echo $approved->pagination['page']; ?><?php if ($approved->needsPagination()) { echo ' &mdash; '; $approved->pagination(); } ?>
						</td>
					</tr>
				</tfoot>
				<tbody>
<?php foreach($approved->items as $post) { ?>
					<tr<?php $post->the_row_info(); ?>>
						<td class="checkbox"><input type="checkbox" name="mass_delete[]" value="<?php $post->the_id(); ?>" /></td>
						<td><?php $post->the_title(); ?></td>
						<td><?php $post->the_date(); ?></td>
						<td><?php $post->the_categories(); ?></td>
						<td><?php $post->the_comment_link(true, array('text'=>$post->get_comment_amount())); ?></td>
						<td class="options"><?php $post->the_options(); ?></td>
					</tr>
<?php } ?>
				</tbody>
			</table>
		</form>
<?php
	}
	
	if ($unapproved->total > 0) {
?>
		<h2>Unapproved Posts <small>(<?php echo $unapproved->total; ?>)</small> <span>(<a href="write.php">add one?</a>)</span></h2>
		<form action="mass-delete.php?type=posts" method="post">
			<table>
				<thead>
					<tr>
						<th><input type="checkbox" /></th>
						<th>Title</th>
						<th>Date</th>
						<th>Categories</th>
						<th>Comments</th>
						<th>&nbsp;</th>
					</tr>
				</thead>
				<tfoot>
					<tr>
						<td colspan="6">
							<input type="submit" name="submit" class="button" value="Delete" />
							Page: <?php echo $approved->pagination['page']; ?><?php if ($unapproved->needsPagination()) { echo ' &mdash; '; $unapproved->pagination(); } ?>
						</td>
					</tr>
				</tfoot>
				<tbody>
<?php foreach($unapproved->items as $post) { ?>
					<tr<?php $post->the_row_info(); ?>>
						<td class="checkbox"><input type="checkbox" name="mass_delete[]" value="<?php $post->the_id(); ?>" /></td>
						<td><?php $post->the_title(); ?></td>
						<td><?php $post->the_date(); ?></td>
						<td><?php $post->the_categories(); ?></td>
						<td><?php $post->the_comment_link(true, array('text'=>$post->get_comment_amount())); ?></td>
						<td class="options"><?php $post->the_options(); ?></td>
					</tr>
<?php } ?>
				</tbody>
			</table>
		</form>
<?php
	}
	
	if ($approved->total === 0 && $unapproved->total === 0) {
?>
		<h2>No Posts<span>(<a href="write.php">add one?</a>)</span></h2>
		<form action="mass-delete.php?type=posts" method="post">
			<table  width="100%">
				<thead>
					<tr>
						<th><input type="checkbox" /></th>
						<th>Title</th>
						<th>Date</th>
						<th>Categories</th>
						<th>Comments</th>
						<th>&nbsp;</th>
					</tr>
				</thead>
				<tfoot>
					<tr>
						<td colspan="6">
							<input type="submit" name="submit" class="button" value="Delete" />
							Page: <?php echo $approved->pagination['page']; ?>
						</td>
					</tr>
				</tfoot>
				<tbody>
					<tr>
						<td colspan="6">No posts found.</td>
					</tr>
				</tbody>
			</table>
		</form>
<?php
	}
	
	get_footer();
}
?>